package com.gao.flying.mq.consumer;

import com.gao.flying.mq.core.JmsContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;


public class JmsDurableConsumer implements Runnable {

    private MessageListener messageListener = null;

    private JmsContext jmsContext;

    private String destinationName;
    private String clientId;

    private static Logger logger = LoggerFactory.getLogger(JmsDurableConsumer.class);

    public JmsDurableConsumer(String clientId, String destinationName, JmsContext jmsContext, MessageListener messageListener) {
        this.destinationName = destinationName;
        this.messageListener = messageListener;
        this.jmsContext = jmsContext;
        this.clientId = clientId;
    }

    @Override
    public void run() {

        try {
            Connection connection = jmsContext.getConnection();
            connection.setClientID(clientId);
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic(destinationName);
            MessageConsumer messageConsumer = session.createDurableSubscriber(topic, clientId);
            messageConsumer.setMessageListener(messageListener);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

}
